<template>
  <div class="file-upload">
    <div style="display: flex; flex-wrap: wrap;">
      <div class="train-module" style="width: 100%; max-width: 600px;">
        <!-- 第一个位置的代码 -->
        <dv-loading v-if="loading" style="height: 20px;margin: 0 auto">Waiting...</dv-loading>
      </div>
      <div style="width: 100%; max-width: 600px;">
        <!-- 第二个位置的代码 -->
        <div
            style="width: 100%;display: flex;flex-direction: row;justify-content: center;margin-top: 20px;">
          <div class="train-module" style="">
            <div style="display: flex;">
              <h2 class="model-name">当前模型：</h2>
              <h2 style="padding-left: 20px">{{
                  $store.state.selectmodel.name
                }}</h2>
            </div>
            <div>
              <div style="display: flex;margin-top: 10px">
                <h2>{{ selectedData }}:</h2>
                <h2 style="padding-left: 40px">{{ trainname.name }}</h2>
              </div>
              <div style="text-align:center;margin-top: 20px;">
                <select v-model="trainData" @change="handleTrainDataChange" style="width: 200px;height: 40px"
                        class="current-model">
                  <option value="" selected disabled>请选择</option>
                  <option v-for="item in datalist" :value="item" :key="item.id">{{ item.name }}</option>
                </select>
                <button class="upload-btn upload-train-btn" :class="{ 'btn-disabled': !trainDataFile }"
                        :disabled="!trainDataFile" @click="startTrain">开始训练
                </button>
                <div style="height: 20px;"></div>
                <select v-model="testData" @change="handleTestDataChange" style="width: 200px;height: 40px"
                        class="current-model">
                  <option value="" selected disabled>请选择</option>
                  <option v-for="item in datalist" :value="item" :key="item.id">{{ item.name }}</option>
                </select>
                <button class="upload-btn upload-train-btn" :class="{ 'btn-disabled': !testDataFile }"
                        :disabled="!testDataFile" @click="startTest">开始预测
                </button>
              </div>
            </div>
            <div style="text-align:center;margin-top: 20px;">
              <button class="upload-btn upload-train-btn" :class="{ 'btn-disabled': !isShowJson }"
                      v-if="isShowJson"
                      :disabled="!isShowJson"
                      @click="startDownloadJson">导出json文件
              </button>
              <button class="upload-btn upload-train-btn" :class="{ 'btn-disabled': !isTxt }"
                      v-if="isTxt"
                      :disabled="!isTxt"
                      @click="startDownloadTxt">导出report
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import dvButton from "_c/dv-button";
import {getFileData} from "@/api/data";
import {startPredict, startTrainModel} from "@/api/model";

export default {
  data() {
    return {
      selectedData: '训练数据',
      isTxt: false,
      trainData: null,
      testData: null,
      datalist: [],
      trainname: "",
      trainDataFile: false,
      testDataFile: false,
      isShowJson: false,
      predictData: {},
      loading: false,
      getedData: null,
    };
  },
  components: {
    dvButton
  },
  mounted() {
    //获取上传数据的信息
    this.getData()
  },
  methods: {
    // todo 下载txt文件
    // todo
    startDownloadTxt() {
      const data = this.getedData; // 假设数据保存在res.data中
      // 将数据转换为字符串格式
      const content = JSON.stringify(data);
      // 创建一个a标签
      const link = document.createElement('a');
      link.href = 'data:text/plain;charset=utf-8,' + encodeURIComponent(content);
      link.download = 'data.txt';
      // 模拟用户点击下载链接
      link.click();
    },
    // todo
    startDownloadJson() {
      var jsonStr = JSON.stringify(this.predictData); // 将字典转换为 JSON 字符串
      var blob = new Blob([jsonStr], {type: 'application/json'}); // 创建新的 Blob 对象
      var url = URL.createObjectURL(blob); // 获取 Blob 对象的访问地址
      // 创建一个 <a> 标签用于下载
      var a = document.createElement('a');
      a.href = url;
      a.download = 'data.json'; // 下载文件的文件名
      document.body.appendChild(a);
      a.click();
    },
    //获取上传的数据信息
    getData() {
      //todo
      getFileData().then(res => {
        this.datalist = res.data.msg
      })
    },
    //当选择我们的trainData之后的时候
    handleTrainDataChange() {
      this.selectedData = '训练数据';
      this.trainDataFile = true
      this.testDataFile = false
      this.trainname = this.trainData
      this.testData = null
    },
    handleTestDataChange() {
      this.selectedData = '预测数据';
      this.testDataFile = true
      this.trainDataFile = false;
      this.trainData = null
      this.trainname = this.testData
    },
    // 将选择的训练数据文件保存在trainDataFile变量中
    handleTrainDataFileChange(event) {
      this.trainDataFile = event.target.files[0];
    },
    // 上传训练数据文件
    startTrain() {
      //开始进行训练
      //获取到我们的模型文件和我们的数据文件
      // todo 如果没有选择模型的话 也是不可以进行训练的 这个时候进行直接一个提示
      let selectModel = this.$store.state.selectmodel
      if (JSON.stringify(selectModel) === JSON.stringify({})) {
        //不能进行训练
        this.$message.error('当前还没有选择模型')
        return;
      }
      let formData = new FormData()
      formData.append("dataId", this.trainData.id)
      this.loading = true
      startTrainModel(selectModel.id, formData).then(res => {
        //todo 提交我们的数据集
        var data = res.data;
        this.getedData = res.data
        this.isTxt = true
        this.isShowJson = false
        this.loading = false;
        this.$bus.$emit('getTrainData', data);
        this.$bus.$emit('chanLoadingTrainState');
      }).catch(() => {
        //处理上传数据的问题
        this.$message.error('数据集上传错误,请仔细检查上传的数据')
        this.loading = false
      })
    },
    startTest() {
      //开始进行训练
      //获取到我们的模型文件和我们的数据文件
      let selectModel = this.$store.state.selectmodel
      if (JSON.stringify(selectModel) === JSON.stringify({})) {
        //不能进行训练
        this.$message.error('当前还没有选择模型')
        return;
      }
      let formData = new FormData()
      formData.append("dataId", this.testData.id)
      this.loading = true
      startPredict(selectModel.id, formData).then(res => {
        // todo
        var data = res.data
        this.loading = false
        this.predictData = data
        this.isShowJson = true
        this.isTxt = false
        var arr = Object.entries(data).map(([id, value]) => ({id, value}));
        this.$bus.$emit('getPredictData', arr)
      }).catch(() => {
        //处理上传数据的问题
        this.$message.error('数据集上传错误,请仔细检查上传的数据')
        this.loading = false
      })
    },
  }
}
</script>

<style scoped>
.file-upload {
  width: 100%;
  height: 400px;
  padding-top: 30px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.model-name {
  color: #fff;
  margin-bottom: 16px;
  text-align: center;
}

.upload-module {
  display: flex;
  flex-direction: column;
  margin-right: 32px;
}

.upload-input {
  display: none;
}

.upload-data {
  display: flex;
  flex-direction: column;
  margin-bottom: 8px;
}

.upload-data span {
  color: #fff;
  margin-right: 8px;
  font-size: 16px;
}

.upload-data p {
  color: #fff;
  margin: 0;
  font-size: 16px;
  padding: 4px 8px;
  border-radius: 4px;
  background-color: #3a8cff;
}

.placeholder {
  color: #ffffff;
  font-style: italic;
}

.upload-btn {
  border: none;
  color: #fff;
  font-weight: bold;
  padding: 8px 16px;
  border-radius: 4px;
  transition: all .3s ease-in-out;
  cursor: pointer;
  font-size: 24px;
  margin-top: auto;
}

.upload-train-btn {
  background-color: #1e67d5;
}

.upload-test-btn {
  background-color: #0a48a6;
}

.btn-disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* hover动态效果 */
.upload-btn:hover:not(.btn-disabled) {
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
}

.upload-btn:focus:not(.btn-disabled) {
  outline: none;
  box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.8);
}

</style>
<style>
.current-model {
  margin-right: 20px;
  color: #d3d6dd;
}

select.current-model {
  border: 2px solid #00b3ff;
  border-radius: 5px;
  background-color: #0a1c3b;
  font-size: 18px;
}

.current-model option {
  width: 100px;
  font-size: 12px;
  outline: none;
}

.current-model .el-select-dropdown__item {
  font-size: 12px;
}

</style>